package com.yangff.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MathUtil {
    private static final String const_salt = "com.yangff.fts";

    public static double getRandomNumberInDoubleRange(double s, double e) {
        Random random = new Random();
        return s + random.nextDouble() * (e - s); // 生成 [s, e] 范围内的随机数
    }

    public static Integer getRandomNumberInIntegerRange(Integer s, Integer e) {
        Random random = new Random();
        return s + random.nextInt(e - s + 1);
    }

    public static Integer getRiskLevel(double sigma,double s, double e) {
        return (int)(1 + (sigma - s) / (e - s) * 9);
    }

    public static String hashWithSHA256(String input) throws NoSuchAlgorithmException {

            //加一个简单的固定盐值，所以盐值不公布
            input += const_salt;
            // 获取SHA-256的消息摘要实例
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 更新摘要，使用指定的字节数组
            byte[] encodedhash = digest.digest(input.getBytes());

            // 将字节转换为十六进制格式
            StringBuilder hexString = new StringBuilder();
            for (byte b : encodedhash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();

    }

    public static boolean checkSHA256(String input, String targetHash) throws NoSuchAlgorithmException {
        String hashedInput = hashWithSHA256(input);
        return hashedInput.equals(targetHash);
    }



}
